package com.mdinic.blogovi.front.common;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.panel.Panel;

public abstract class AbstractMorePage<T> extends AbstractBasePage {

    private static final long serialVersionUID = -299670536679466105L;

    private final int firstResult;

    private int page = 1;

    private final List<T> list = new ArrayList<T>();

    public AbstractMorePage(final int maxResults, boolean needUser) {
        super(needUser);
        this.firstResult = maxResults;

        list.addAll(getList(0, maxResults));

        final Panel blogPostPanel = createPanel(list);
        blogPostPanel.setOutputMarkupId(true);
        add(blogPostPanel);

        AjaxLink<Void> more = new AjaxLink<Void>("more_link") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                List<T> toAdd = getList(firstResult * page, maxResults);

                if (!toAdd.isEmpty()) {
                    list.addAll(toAdd);
                    target.add(blogPostPanel);
                    page++;
                } else {
                    Component component = getPage().get("more_link");
                    component.setEnabled(false);
                    target.add(component);
                }
            }
        };
        more.setOutputMarkupId(true);
        add(more);

    }

    protected abstract List<T> getList(int firstResult, int maxResults);

    protected abstract Panel createPanel(List<T> list);

}
